import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';

class HttpDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('HttpDemo'),
        elevation: 0.0,
      ),
      body: HttpDemoHome(),
    );
  }
}

class HttpDemoHome extends StatefulWidget {
  @override
  _HttpDemoHomeState createState() => _HttpDemoHomeState();
}

class _HttpDemoHomeState extends State<HttpDemoHome> {
  @override
  void initState() {
    super.initState();
    // fetchPosts()
    //   .then((value) => print(value));

    // final post = {
    //   'title': 'hello',
    //   'description': 'nice to meet you.',
    // };

    // print(post['title']);
    // print(post['description']);

    // final postJson = json.encode(post);
    // print(postJson);

    // final postJsonConverted = json.decode(postJson);
    // print(postJsonConverted['title']);
    // print(postJsonConverted['description']);
    // print(postJsonConverted is Map);

    // final postModel = Post.fromJson(postJsonConverted);
    // print('title: ${postModel.title}, description: ${postModel.description}');

    // print('${json.encode(postModel)}');
  }

  Future fetchPosts() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    // 获得密码
    final codeResponse = await http.get(
      'https://me.yuanqiao.pw/api/me/getList.php?limit=20&offset=0',
      headers: {HttpHeaders.authorizationHeader: prefs.get('user_token')},
    );
    if (codeResponse.statusCode == 200) {
      final codeResponseBody = json.decode(codeResponse.body);
      if(codeResponseBody['state'] == '3') {
        Navigator.of(context).pushNamedAndRemoveUntil('/login', (route) => route == null,);
      }
      List<Post> posts = codeResponseBody['data']
        .map<Post>((item) => Post.fromJson(item))
        .toList();
      print(posts);
      return posts;
    }
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: fetchPosts(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        print('data: ${snapshot.data}');
        print('connectionState: ${snapshot.connectionState}');
        if (snapshot.connectionState == ConnectionState.waiting) {
          return Center(
            child: Text('loading...'),
          );
        }
        return ListView(
          children: snapshot.data.map<Widget>((item) {
            return ListTile(
              title: Text(item.username),
              subtitle: Text(item.website)
            );
          }).toList(),
        );
      },
    );
  }
}

class Post {
  final String id;
  final String website;
  final String date;
  final String email;
  final String username;
  final String weblink;
  final String userid;
  final String password;
  final String passwordText;
  final String remark;

  Post(
    this.id,
    this.website,
    this.date,
    this.email,
    this.username,
    this.weblink,
    this.userid,
    this.password,
    this.passwordText,
    this.remark
  );

  Post.fromJson(Map json)
    : id = json['id'],
      website = json['website'],
      date = json['date'],
      email = json['email'],
      username = json['username'],
      weblink = json['weblink'],
      userid = json['userid'],
      password = json['password'],
      passwordText = json['passwordText'],
      remark = json['remark'];

  Map toJson() => {
    'username': username,
    'website': website,
  };
}
